package com.sws.orderMS.command.impl;

import java.util.ArrayList;
import java.util.List;

import com.sws.orderMS.OrderMSDao;
import com.sws.orderMS.command.UserCommand;
import com.sws.orderMS.pojo.Order;
import com.sws.orderMS.pojo.OrderItem;
import com.sws.orderMS.pojo.Product;
import com.sws.orderMS.pojo.User;
import com.sws.orderMS.tool.Tool;

public class ListMyOrderCommand extends UserCommand {

	public ListMyOrderCommand(User userProfile) {
		super(userProfile);
	}

	@Override
	public void execute() {
		String mode = Tool.askUserInputNotNull("选择你要列出的订单方式(ALL|PRODUCT|DONE|UNDONE): ");
		
		if (!"ALL|PRODUCT|DONE|UNDONE".contains(mode.toUpperCase())) {
			Tool.printMsg("Invalid mode!");
			return;
		}
		
		OrderMSDao dao = new OrderMSDao();
		List<Order> orders = new ArrayList<>();
		
		if ("ALL".equalsIgnoreCase(mode)) {
			orders = dao.searchAllOrders(userProfile);
		} else if ("PRODUCT".equalsIgnoreCase(mode)) {
			String productName = Tool.askUserInputNotNull("请输入商品名称:");
			List<Order> tempList = dao.searchAllOrders(userProfile);
			for (Order order: tempList)	{
				List<OrderItem> itemList = order.getOrderList();
				for (OrderItem item: itemList) {
					if (item.getProduct().getName().equals(productName)) {
						orders.add(order);
						break;
					}
				}
			}
			if (orders.isEmpty()) {
				Tool.printMsg("没有找到包含商品 " + productName + " 的订单");
				return;
			}
		} else if ("DONE".equalsIgnoreCase(mode)) {
			List<Order> tempList = dao.searchAllOrders(userProfile);
			for (Order order: tempList) {
				if (order.getCurrentStatus() == 4) {
					orders.add(order);
				}
			}
		} else if ("UNDONE".equalsIgnoreCase(mode)) {
			List<Order> tempList = dao.searchAllOrders(userProfile);
			for (Order order: tempList) {
				if (order.getCurrentStatus() != 4) {
					orders.add(order);
				}
			}
		}
		if (orders.isEmpty()) {
			Tool.printMsg("暂无订单");
			return;
		}
		showOrders(orders);
	}

	private void showOrders(List<Order> orders) {
		for (Order order: orders) {
			String status = order.getOrderStatus(order.getCurrentStatus());
			if (order.getCurrentStatus() != 4) {
				status = order.getPaymentStatus(order.getCurrentPaymentStatus());
			}
			Tool.printMsg("订单号:" + order.getOrderNo() + 
					", 订单状态:" + status);
			for (OrderItem item: order.getOrderList()) {
				Tool.printMsg(item.getProduct().getName() + "\t\t" + "x" + item.getAmount());
			}
			
			int num = 0;
			for (OrderItem item: order.getOrderList()) {
				num = num + item.getAmount();
			}
		
			double pay = 0;
			if (order.getCurrentStatus() == 4) {
				pay = order.getTotal();
			}
			String total = pay == 0 ? "" : ", 实付" + pay + "元";
			Tool.printMsg("共" + num + "件商品" + total);
			
		}
	
	}

}
